package com.jx.service.lmpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jx.dao.AppInfoDao;
import com.jx.dao.AppVersionDao;
import com.jx.dto.AppInfoDto;
import com.jx.entity.AppInfo;
import com.jx.entity.AppVersion;
import com.jx.service.AppInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

@Service
public class AppInfoServicelmpl implements AppInfoService {

    @Resource
    AppInfoDao appInfoDao;

    @Resource
    AppVersionDao appVersionDao;

    @Override
    public PageInfo<AppInfo> page(AppInfoDto appInfoDto, Integer num) {
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(appInfoDto,appInfo);
        PageHelper.startPage(num,10,"id desc");
        List<AppInfo> appInfos = appInfoDao.queryAll(appInfo);
        return new PageInfo<>(appInfos);
    }

    @Override
    public void getInsOrUpdate(AppInfo appInfo) {
        if (appInfo.getId()==null) {
            appInfoDao.insert(appInfo);
        }
        else {
            appInfoDao.update(appInfo);
        }
    }

    @Override
    public AppInfo updateId(Long id) {
        AppInfo appInfo = appInfoDao.queryById(id);
        return appInfo;
    }

    @Override
    public void getStatus(Long id) {
        AppInfo appInfo = appInfoDao.queryById(id);
        if (appInfo.getStatus()==4){
            appInfo.setStatus(5L);
        }
        else if (appInfo.getStatus()==5||appInfo.getStatus()==2){
            appInfo.setStatus(4L);
        }
        appInfoDao.update(appInfo);
    }

    @Override
    public void del(Long id, HttpServletRequest request) {
        AppVersion appVersion = new AppVersion();
        appVersion.setAppid(id);
        List<AppVersion> appVersions = appVersionDao.queryAll(appVersion);
        for (AppVersion version : appVersions) {
            String realPath = request.getServletContext().getRealPath(version.getDownloadlink());
            File file = new File(realPath);
            file.delete();
        }

        appVersionDao.deleteById(id);

        AppInfo appInfo = appInfoDao.queryById(id);
        String realPath = request.getServletContext().getRealPath(appInfo.getLogopicpath());
        File file = new File(realPath);
        file.delete();

        appInfoDao.deleteById(id);
    }

    @Override
    public Boolean selApkName(String apkName, Long id) {
        int i = appInfoDao.selApkName(apkName);
        if (id!=null) {
            AppInfo appInfo = appInfoDao.queryById(id);
            if (appInfo.getApkname().equals(apkName)) {
                return true;
            }
        }
        if (i>0){
            return false;
        }

        return true;
    }
}
